var express = require("express")
var router = express.Router()

const { getAll, getById, exec, getOne } = require("../db")

/**
 * 获取所有用户报告的事件
 * GET /event
 */

router.get("/", async (req, res) => {
  const { keyword } = req.query
  let sql = ``
  if (!keyword) {
    sql = `select * from gg_event`
    const data = await getAll(sql)
    // console.log(data);
    res.send({
      code: 0,
      message: "获取所数据成功",
      result: data,
    })
  } else {
    console.log(keyword)
    sql = `select * from gg_event where event_type like '%${keyword}%'`
    const data = await getAll(sql)
    console.log(data)
    res.send({
      code: 0,
      message: "获取成功",
      result: data,
    })
  }
})

//根据id获取事件
router.get("/:event_id", async (req, res) => {
  const { event_id } = req.params
  let sql = `select * from gg_event where event_id=${event_id}`
  const data = await getOne(sql)
  console.log(data)
  res.send({
    code: 0,
    message: "获取用户成功",
    result: data,
  })
})
/**
 * 添加用户报告的事件
 * POST /event
 */
router.post("/", async (req, res) => {
  const {
    user_id,
    event_type,
    event_addr,
    event_mark,
    event_describe,
    event_status,
    user_name,
  } = req.body
  console.log(user_name)
  let sql = `insert into gg_event (user_id,event_type, event_addr, event_mark, event_describe,event_status,user_name) 
  values ('${user_id}', '${event_type}' , '${event_addr}','${event_mark}','${event_describe}','${event_status}','${user_name}')`

  const data = await exec(sql)
  console.log(111)
  res.send({
    code: 0,
    message: "添加数据成功",
    result: {
      event_id: data.insertId,
      event_type,
      event_addr,
      event_mark,
      event_describe,
      event_status,
      user_name,
    },
  })
})

/*
 * 审核（修改）
 * put/:id
 */

router.put("/:event_id", async (req, res) => {
  // 根据id修改
  const { event_id } = req.params
  console.log(req.params)
  // 审核
  const { event_status } = req.body
  console.log(req.body)
  let sql = `update gg_event set event_status='${event_status}' where event_id ='${event_id}'`
  const data = await exec(sql)
  // console.log(data);
  res.send({
    code: 0,
    message: "审核通过",
    result: {
      event_id,
      event_status,
    },
  })
})

/**
 * 删除用户报告的事件
 * DELETE /event
 */
router.delete("/:id", async (req, res) => {
  const { id } = req.params
  console.log(id)
  let sql = `delete from gg_event where event_id=${id}`
  try {
    await exec(sql)
    res.send({
      code: 0,
      message: "删除数据成功",
    })
  } catch (error) {
    res.send({
      code: 100101,
      message: "删除数据失败",
    })
  }
})
module.exports = router
